<!DOCTYPE html>
<%@ page language="java" import="com.compuvest.web.*,com.compuvest.ics.ICSAuth,com.compuvest.webstatus.*,java.text.*,java.util.*" pageEncoding="UTF-8" %>

<jsp:useBean id="sb" class="SQLBean" scope="application"/>
<jsp:useBean id="ics" class="ICSAuth" scope="application"/>
<jsp:useBean id="mail" class="Mail" scope="application"/>
<jsp:useBean id="advertShow" class="AdvertShow" scope="application"/>
<jsp:useBean id="basket" class="Basket" scope="session"/>

<%!
    public static final int APPEND_OK = 0;
    public static final int APPEND_A = 1;
    public static final int APPEND_B = 2;
    public static final int APPEND_C = 3;
    public static final int APPEND_D = 4;
    public static final int APPEND_E = 5;

    public static final String[] rules = {
/*0*/ "Your order is now being processed!\n",
/*1*/ "<b>If you are a new CompuVest customer, please read the following:</b><br/><br/> 1. Since your billing address was different from shipping, you must fax a signed form authorizing us to ship the product to that particular shipping address. Please download the <a href='../img/form/form.rtf'><font color='red'>FORM</font></a>, print it, fill it out and fax to: 425-251-5000 Att: your order confirmation number, or sales order number.<br/>",
/*2*/ "<br/>2. You must call American Express customer service to add your \"ship to address\" on file as the Authorized Shipping address. This is a regular procedure for American Express. We always check if the credit card company has an authorized shipping address on cardholder's file before shipping the order.<br/>",
/*3*/ "<br/>2. You must call Discover customer service to add your \"ship to address\" on file as the Authorized Shipping address. This is a regular procedure for Discover. We always check if the credit card company has an authorized shipping address on cardholder's file before shipping the order.<br/>",
/*4*/ "<br/>2. Fax the front and back of the credit card used for the order to: 425-251-5000 along with the authorization form.<br/>",
/*5*/ "Your order exceeds $5000.00 and the shipping address is different from billing. In this case we do not guarantee the processing of the order as we need to verify the information you supplied. Someone will contact you shortly to go over payment details.<br/>"
    };

    public String checkPayment(Basket basket) {

	Customer cust = basket.getCustomer();

	if(!cust.compareBillingAndShipping() && basket.getPaymentMethod().equals("CC")) {

            if(basket.getGrandTotal() >= 100d && basket.getGrandTotal() <= 700d) {

		if(cust.getCType().equals("VISA") || cust.getCType().equals("MASTERCARD")) return rules[APPEND_A];
                else if(cust.getCType().equals("AMEX")) return rules[APPEND_A] + rules[APPEND_B];
                else if(cust.getCType().equals("DISCOVER")) return rules[APPEND_A] + rules[APPEND_C];
                else return rules[APPEND_OK];
            }
            else if(basket.getGrandTotal() >= 700d && basket.getGrandTotal() <= 5000d) {

                if(cust.getCType().equals("VISA") || cust.getCType().equals("MASTERCARD")) return rules[APPEND_A] + rules[APPEND_D];
                else if(cust.getCType().equals("AMEX")) return rules[APPEND_A] + rules[APPEND_B];
                else if(cust.getCType().equals("DISCOVER")) return rules[APPEND_A] + rules[APPEND_C];
                else return rules[APPEND_OK];
            }
            else if(basket.getGrandTotal() >= 5000d) {
                if(cust.getCType().equals("VISA") || cust.getCType().equals("MASTERCARD") ||
                    cust.getCType().equals("AMEX") || cust.getCType().equals("DISCOVER")) {
                    return rules[APPEND_E];
                }
                return rules[APPEND_OK];
            }
	}
	return rules[APPEND_OK];
    }

    Items basketItems = new Items(); // for getResellerPriceLine()
%>
<%
    if(basket.isEmpty() || (basket.getGrandTotal() == 0d)) {
	response.sendRedirect(session.getAttribute("backItemsPage") == null ? application.getInitParameter("http") : (String)session.getAttribute("backItemsPage"));
	return;
    }

    Customer cust = basket.getCustomer();
    if(cust == null) {
        response.sendRedirect(application.getInitParameter("https") + "CustomerForm.jsp");
        return;
    }

    DecimalFormat priceForm = new DecimalFormat("$#,##0.00");
    DecimalFormat number = new DecimalFormat("#0.00");
    DecimalFormat simple = new DecimalFormat("#0");
    SimpleDateFormat dateForm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    String checkResult = checkPayment(basket);

    // write order to database and update old customer or make new customer
    String orderNumber = "200808088888";
    orderNumber = sb.makeOrder(basket, advertShow);
    basket.setOrderNumber(orderNumber);

    String icsStat = "";

    if("PP".equals(basket.getPaymentMethod())) {
        ;//nothing
    }
    else if("WT".equals(basket.getPaymentMethod())) {
        ;//nothing
    }
    else if("UN".equals(basket.getPaymentMethod())) {
        ;//nothing
    }
    else { // CC - CreditCard & CD - by Check (telecheck)
        if(cust.getBilling().getState().equals(cust.getShipping().getState()) || (basket.getGrandTotal() > 100d)) { // send to cybersourse if billing.Stat=shipping.State or total > $100

            if(!cust.getCType().equals("AMEX") || (basket.getGrandTotal() < 100d)) { // if AMEX send money if lt $100.00
                icsStat = ics.getICSStat(basket);
                sb.setOrderStatus(orderNumber, icsStat); // write status auth order to database
            }
        }
    }
    String advertName = basket.getCompuvestCookies().getAdvertSite();

    mail.sendEmail(basket, icsStat);
%>
<html>
<head>
<title><%= application.getInitParameter("CompanyName") %></title>
<%@include file="./incl/scripts.txt" %>
</head>
<body>

<%
    StringBuilder body = new StringBuilder(4000);
    body.append("<div class='cstyle'>\n");
    body.append("<fieldset>\n");
    body.append("<div class='cont'>\n");
    body.append("<table style='width:100%;margin:2px 2px;'>\n");
    body.append("<tr>");
    body.append("<td colspan='2'>");
    body.append("<img src='../img/hd/hlogo.png' alt=''/>");
    body.append("<div class='tit' style='text-align:center;'>Compuvest.com&copy; Corporation, 3600 Lind Ave. S.W, Suite 130, Renton, WA 98057 USA.</div>");
    body.append("<br/><div class='tit'>&nbsp;&nbsp;Tel: (425) 738-4091</div>");
    body.append("<div class='tit'>&nbsp;&nbsp;Fax: (425) 251-5000</div>");
    body.append("<div class='tit' style='text-align:right;'>").append(dateForm.format(new java.util.Date())).append("&nbsp;&nbsp;&nbsp;</div>");
    if(basket.getReseller()) {
	body.append("<div class='tit'>&nbsp;&nbsp;Reseller ID: ").append(cust.getResellerCode()).append("</div>");
    }
    body.append("<hr/>");
    body.append("<div class='tit' style='text-align:center;'><font size='2'>Order <font color='red'>").append(basket.getOrderNumber()).append("</font> Confirmation</font></div>");
    body.append("<br/>");
    body.append("</td>");
    body.append("</tr>\n");

    body.append("<tr>");
    body.append("<td style='vertical-align:top;width:50%;'>");
    body.append("<div class='tit' style='padding:2px 6px;'>Billing Address:<br/>");
    body.append("<span style='font-weight:normal;'>");
    body.append(cust.getBilling().getCompany()).append("<br/>");
    body.append(cust.getBilling().getName()).append("<br/>");
    body.append(cust.getBilling().getAddress1()).append(' ');
    body.append(cust.getBilling().getAddress2()).append(' ');
    body.append(cust.getBilling().getCity()).append(",");
    body.append(cust.getBilling().getState()).append(' ');
    body.append(cust.getBilling().getZip()).append(' ');
    body.append(cust.getBilling().getZip4()).append(' ');
    body.append(cust.getBilling().getCountry()).append("<br/>");
    body.append("Tel: ").append(cust.getBilling().getPhone()).append("<br/>");
    if(!cust.getBilling().getCell().isEmpty()) {
	body.append("Cell: ").append(cust.getBilling().getCell()).append("<br/>");
    }
    if(!cust.getBilling().getFax().isEmpty()) {
	body.append("Fax: ").append(cust.getBilling().getFax());
    }
    body.append("</span></div>");
    body.append("</td>");
    body.append("<td style='vertical-align:top;width:50%;'>");
    body.append("<div class='tit' style='padding:2px 6px;'>").append(basket.getBlindShipping() ? "<font color='red'>Blind</font> " : "").append("Shipping Address:<br/>");
    body.append("<span style='font-weight:normal;'>");
    body.append(cust.getShipping().getCompany()).append("<br/>");
    body.append(cust.getShipping().getName()).append("<br/>");
    body.append(cust.getShipping().getAddress1()).append(' ');
    body.append(cust.getShipping().getAddress2()).append(' ');
    body.append(cust.getShipping().getCity()).append(",");
    body.append(cust.getShipping().getState()).append(' ');
    body.append(cust.getShipping().getZip()).append(' ');
    body.append(cust.getShipping().getZip4()).append(' ');
    body.append(cust.getShipping().getCountry()).append("<br/>");
    body.append("Tel: ").append(cust.getShipping().getPhone()).append("<br/>");
    if(!cust.getShipping().getCell().isEmpty()) {
	body.append("Cell: ").append(cust.getShipping().getCell()).append("<br/>");
    }
    if(!cust.getShipping().getFax().isEmpty()) {
	body.append("Fax: ").append(cust.getShipping().getFax());
    }
    body.append("</span></div>");
    body.append("</td>");
    body.append("</tr>\n");

    body.append("<tr>");
    body.append("<td colspan='2'><br/>");
    body.append("<table class='part' style='width:99%;border-color:#d4d4d4;' border='1'>");
    body.append("<colgroup><col width='11%'/><col width='53%'/><col width='6%'/><col span='3' width='10%'/></colgroup>");
    body.append("<tr class='bsm' height='30'><th>Part #</th><th>Product Name</th><th>Qty</th><th>Price</th><th>Extended Warranty</th><th>Amount</th></tr>");

    boolean isGrabber = (advertShow.getAdvertID(advertName) == AdvertShow.GRABBER);
    StringBuilder priceGrabber = null;
    if(isGrabber) {
	priceGrabber = new StringBuilder(150);
	priceGrabber.append("<img src='https://www.pricegrabber.com/conversion.php?retid=17");
    }
    boolean isNexttag = (advertShow.getAdvertID(advertName) == AdvertShow.NEXTTAG);
    StringBuilder nexttag = null, nextCat = null, nextName = null, nextAccware = null;
    if(isNexttag) {
	nexttag = new StringBuilder(150);
	nextCat = new StringBuilder();
	nextName = new StringBuilder();
	nextAccware = new StringBuilder();
	nexttag.append("<script type=\"text/javascript\">\n");
	nexttag.append("var id='1326';\n");
	nexttag.append("var rev='").append(String.format("%.2f", basket.getTotal(true) + basket.getTaxCost())).append("';\n");
	nexttag.append("var order='").append(basket.getOrderNumber()).append("';\n");
    }
    boolean isBing = (advertShow.getAdvertID(advertName) == AdvertShow.BING);
    StringBuilder bing = null;
    if(isBing) {
	bing = new StringBuilder(150);
	bing.append("<script type=\"text/javascript\">\n");
	bing.append("var jf_merchant_id='MXF5RkhqNnM1YWJLa0JkMkxEeWZoQT09Cg';\n");
	bing.append("var jf_merchant_order_num='").append(basket.getOrderNumber()).append("';\n");
	bing.append("var jf_purchased_items=new Array();\n");
    }
    boolean isLinkShare = (advertShow.getAdvertID(advertName) == AdvertShow.LINKSHARE);
    StringBuilder links = null, skulist = null, qlist = null, amtlist = null;
    if(isLinkShare) {
	links = new StringBuilder(150);
	skulist = new StringBuilder();
	qlist = new StringBuilder();
	amtlist = new StringBuilder();
	links.append("<img src=\"https://track.linksynergy.com/ep?mid=36385&cur=USD&ord=").append(basket.getOrderNumber());
    }
    // -------------------------
    boolean ground = false;
    int index = 1, idx = 0;
    String prefix = "";
    for(ItemsInBasket item : basket.getContents()) {
	if(isGrabber) {
            priceGrabber.append("&item").append(index).append('=').append(item.getMfrName()).append('|');
            priceGrabber.append(item.getMfrNumber()).append('|');
            priceGrabber.append(number.format(item.getSellPrice())).append('|');
            priceGrabber.append(item.getAccwareCode()).append('|');
            priceGrabber.append(basket.getOrderNumber()).append('|');
            priceGrabber.append(item.getTotalQuantity());
	}
	if(isNexttag) {
            nextCat.append(item.getCategoryName()).append('|');
            nextName.append(item.getItemName()).append('|');
            nextAccware.append(item.getAccwareCode()).append('|');
	}
	if(isBing) {
            bing.append("var jf_item=new Object();\n");
            bing.append("jf_item.mpi='").append(item.getAccwareCode()).append("';\n");
            bing.append("jf_item.price='").append(number.format(item.getSellPrice())).append("';\n");
            bing.append("jf_item.quantity='").append(item.getTotalQuantity()).append("';\n");
            bing.append("jf_purchased_items.push(jf_item);\n");
	}
        if(isLinkShare) {
            prefix = idx++ > 0 ? "|" : "";
            skulist.append(prefix).append(item.getAccwareCode());
            qlist.append(prefix).append(item.getTotalQuantity());
            amtlist.append(prefix).append(simple.format((double)item.getTotalQuantity() * item.getSellPrice() * 100d));
        }
        // -------------------------

	body.append("<tr align='center' height='30' bgcolor='#ffff").append((ground = !ground) ? "df" : "ff").append("'>");
	body.append("<td id='nowrap'>").append(item.getAccwareCode()).append("<div style='font-size:10px;color:blue;'>").append(item.getCondition()).append("</div></td>");
	body.append("<td align='left'><div class='tlink'>").append(item.getItemName()).append("</div>");
	body.append(basket.getReseller() ? basketItems.getResellerPriceLine(item) : "");
	body.append(item.getPromotionPriceString(false));
	body.append("</td>");

	body.append("<td>").append(item.getTotalQuantity()).append("</td>");
	body.append("<td>");
	if(basket.getReseller() && item.getResPrice1() != 0d) {
            body.append("<div class='prices'>").append(priceForm.format(item.getPrice())).append("</div>");
	}
	body.append(priceForm.format(item.getSellPrice()));
	body.append("</td>");
	body.append("<td>").append(item.getWarrantyTotal() == 0d ? "" : priceForm.format(item.getWarrantyTotal()) + "<div style='font-size:10px;color:green;'>" + item.getWarrantyDesc() + "</div>").append("</td>");
	body.append("<td>").append(priceForm.format(item.getSellPrice() * item.getTotalQuantity() + item.getWarrantyPrice() * item.getTotalQuantity())).append("</td>");
	body.append("</tr>");

        index++;
    }
    if(isGrabber) {
        priceGrabber.append("'>\n");
        out.write(priceGrabber.toString());
    }
    if(isNexttag) {
        nexttag.append("var cats='").append(nextCat).append("';\n");//categoryname
        nexttag.append("var prods='").append(nextName).append("';\n");//itemname
        nexttag.append("var units='").append(nextAccware).append("';\n");//accwarecatid
        nexttag.append("</script>\n");
        nexttag.append("<script type='text/javascript' src='https://imgsrv.nextag.com/imagefiles/includes/roitrack.js'></script>\n");
        out.write(nexttag.toString());
    }
    // tracking for bing
    if(isBing) {
        bing.append("</script>\n");
        bing.append("<script type='text/javascript' src='https://ssl.bing.com/cashback/javascripts/1x1tracking.js'></script>\n");
        out.write(bing.toString());
    }
    if(isLinkShare) {
        links.append("&skulist=").append(skulist);
        links.append("&qlist=").append(qlist);
        links.append("&amtlist=").append(amtlist);
        links.append("\"/>");
        out.write(links.toString());
    }
    boolean isCatch = (advertShow.getAdvertID(advertName) == AdvertShow.CATCH);
    if(isCatch) {
	out.write("<img height='1' width='1' border='0' style='display:none;' src='https://www.catchmarketingservices.com/tracker2.php?onum=" + basket.getOrderNumber() + "&oamt=" + number.format(basket.getTotal(true)) + "&var1=CompuVest'/>");
    }

    body.append("<tr><td colspan='6' align='right' style='padding:8px 10px;'>");
    if(basket.getCouponMessage(false).length() > 0) {
        body.append("<p style='color:red;'>").append(basket.getCouponMessage(false)).append("</p>");
    }
    body.append("Total Amount : ").append(priceForm.format(basket.getTotal(true))).append("</td></tr>");
    body.append("</table><br/>\n");

    body.append("<div class='tit' style='text-align:center;font-size:16px;'>Summary</div>");
    body.append("<table class='part' style='width:99%;border-color:#d4d4d4;' border='1'>");
    body.append("<tr class='bsm' height='30'><th width='60%'>&nbsp;</th><th width='20%'>&nbsp;</th><th width='20%'>&nbsp;</th></tr>");

    if(cust.getShipping().getState().equals("WA")) {
	body.append("<tr height='30'><td>WA Tax</td><td>Tax</td><td align='right'>").append(priceForm.format(basket.getTaxCost())).append("</td></tr>");
    }
    if(basket.getSignatureRequired()) {
	body.append("<tr height='30'><td>Signature Required</td><td>Charge</td><td align='right'>").append(priceForm.format(basket.getSignaturePrice())).append("</td></tr>");
    }

    body.append("<tr height='30'>");
    body.append("<td>Shipping Method: ").append(basket.getShippingDescription()).append("</td>");
    body.append("<td>Shipping</td>");
    body.append("<td align='right'>").append(priceForm.format(basket.getShippingCost())).append("</td>");
    body.append("</tr>");

    body.append("<tr height='30'>");
    body.append("<td colspan='2' align='left'>Order Total : <div id='am'>&nbsp;</div></td>");
    body.append("<td id='nsu' align='right' valign='bottom'>").append(priceForm.format(basket.getGrandTotal())).append("</td>");
    body.append("</tr>");
    body.append("</table>");

    body.append("<img src='../img/hd/pix.png' onload='NtoW();' alt=''/><br/>");
    body.append("<hr/>");
    body.append("<div class='tit' style='padding:2px 6px 2px 6px;font-weight:normal;'>").append(checkResult).append("</div>");
    body.append("<br/>");

    body.append("<div style='text-align:right;'>");
    body.append("<font size='2'>Thank you for your Order.</font>&nbsp;&nbsp;&nbsp;&nbsp;");
    body.append("<button onclick='javascript:window.print();'>Print Order Confirmation</button>&nbsp;&nbsp;&nbsp;&nbsp;");
    body.append("<button onclick=\"javascript:location.href='").append(application.getInitParameter("http")).append("'\">Close page</button>&nbsp;&nbsp;");
    body.append("</div>");
    body.append("<br/>");

    body.append("</td></tr>");

    body.append("</table>\n");
    body.append("</div>\n");
    body.append("</fieldset>\n");
    body.append("</div>");
    // end of orders

    if("PP".equals(basket.getPaymentMethod())) {
%>

<br/>

 <form action='https://www.paypal.com/cgi-bin/webscr' method='POST'>
  <div id="tyou">
  <p><b>Thank You for Your Order!</b></p>
  <p><b>Your confirmation number is <tt style="color:green;font-size:20px;"><%= basket.getOrderNumber() %></tt></b></p>
  <p style="color:red;">Your order is <b>NOT COMPLETE.</b><br/>Please click Paypal Checkout Button to finish your order.</p>
  <br/>
  <button type='submit' name='mode'><img alt="Make payment PayPal - it's fast, free and secure!" src='../img/it/paypal_out.gif'/></button>

  <input type='hidden' name='cmd' value='_ext-enter'/>
  <input type='hidden' name='redirect_cmd' value='_cart'/>
<%
    String paypalAccount = "paypal@compuvest.com";
%>
  <input type='hidden' name='business' value='<%= paypalAccount %>'/>
  <input type='hidden' name='no_note' value='1'/>
  <input type='hidden' name='upload' value='1'/>
  <input type='hidden' name='currency_code' value='USD'/>
  <input type='hidden' name='first_name' value='<%= cust.getShipping().getFirstName() %>'/>
  <input type='hidden' name='last_name' value='<%= cust.getShipping().getLastName() %>'/>
  <input type='hidden' name='address1' value='<%= cust.getShipping().getAddress1() %>'/>
  <input type='hidden' name='address2' value='<%= cust.getShipping().getAddress2() %>'/>
  <input type='hidden' name='city' value='<%= cust.getShipping().getCity() %>'/>
  <input type='hidden' name='state' value='<%= cust.getShipping().getState() %>'/>
  <input type='hidden' name='zip' value='<%= cust.getShipping().getZip() %>'/>
  <input type='hidden' name='country' value='<%= cust.getShipping().getCountry() %>'/>
  <input type='hidden' name='email' value='<%= cust.getEmail() %>'/>
  <input type='hidden' name='custom' value='Order <%= basket.getOrderNumber() %>'/>
<%
	int count = 1;
	for(ItemsInBasket item : basket.getContents()) {
%>
  <input type='hidden' name='item_name_<%= count %>' value='<%= item.getItemName() %>'/>
  <input type='hidden' name='quantity_<%= count %>' value='<%= item.getTotalQuantity() %>'/>
  <input type='hidden' name='amount_<%= count %>' value='<%= number.format(item.getSellPrice()) %>'/>
  <input type='hidden' name='item_number_<%= count %>' value='<%= item.getAccwareCode() %>'/>
<%
            if(item.getWarrantyPrice() != 0d) {
                count++;
%>
  <input type='hidden' name='item_name_<%= count %>' value='Extended warranty: <%= item.getWarrantyDesc() %> for SKU #<%= item.getAccwareCode() %>'/>
  <input type='hidden' name='quantity_<%= count %>' value='1'/>
  <input type='hidden' name='amount_<%= count %>' value='<%= number.format(item.getWarrantyTotal()) %>'/>
  <input type='hidden' name='item_number_<%= count %>' value=''/>
<%
	    }
	    count++;
	}
        if(basket.getSignatureRequired()) {
%>
  <input type='hidden' name='item_name_<%= count %>' value='Signature Required'/>
  <input type='hidden' name='quantity_<%= count %>' value='1'/>
  <input type='hidden' name='amount_<%= count %>' value='<%= number.format(basket.getSignaturePrice()) %>'/>
  <input type='hidden' name='item_number_<%= count %>' value=''/>
<%
        }
        if(basket.getCouponPayPalMessage().length() > 0) {
%>
  <%= basket.getCouponPayPalMessage() %>
<%
        }
%>
  <input type='hidden' name='shipping_1' value='<%= number.format(basket.getShippingCost()) %>'/>
  <input type='hidden' name='tax_cart' value='<%= number.format(basket.getTaxCost()) %>'/>

  <p style='text-align:justify;font-size:12px;'><b>Please note:</b><br/>
  To ensure security, this order may require voice confirmation with our Customer Service Department prior to shipping.
  If this necessary, a representative will call or email you while processing you order. We reserve the right to cancel
  any order before it is shipped.
  </p>
 </div>

<%
	out.write(body.toString());
%>
  <div id="tyou">
  <br/>
  <p style="color:red;">Your order is <b>NOT COMPLETE.</b><br/>Please click Paypal Checkout Button to finish your order.</p>

  <br/>
  <button type='submit' name='mode'><img alt="Make payment PayPal - it's fast, free and secure!" src='../img/it/paypal_out.gif'/></button>
  </div>
 </form>

<%
    }
    else { // CC & COD & Western Union
	out.write(body.toString());

    } // all
%>

<div id="vh_container_surveys"  style="position:relative;z-index:9999;width:288px;height:239px">			
 <div id="vh_dataDiv_surveys">
   <iframe src="http://www.verifiedhonest.com/survey/surveys.php?cid=11233&productid=1" frameBorder="0" width="288" height="239" style="border:none;padding:0;margin:0;" id="vh_surveys" name="vh_surveys"></iframe>
 </div>
 <div onclick="document.getElementById('vh_container_surveys').style.display='none';" style="position:absolute;cursor:pointer;top:5px;right:5px;"><img src="http://www.verifiedhonest.com/survey/image/close.png"/></div>
</div>

</body>

<%
    sb.copyToHistory(basket.getOrderID(), body.toString());
    basket.clean();
%>
</html>
